﻿chrome.app.runtime.onLaunched.addListener(function (launchData) {

    var viewerUrl = '';
    var screenWidth = 100;
    var screenHeight = 100;

    console.log(launchData);
    if (launchData) {
      var fileEntry = launchData.intent.data;
      readFile();
    } else {
      console.log('no launchData');
    }

    function startViewer() {
        console.log('screenWidth = ' + screenWidth + '; screenHeight = ' + screenHeight + '; viewerUrl = ' + viewerUrl);

        chrome.app.window.create('index.html', {
            'frame': 'none',
            'left': 0,
            'top': 0,
            'width': screenWidth,
            'height': screenHeight
        },
        function (win) {
            win.contentWindow.launchData = viewerUrl;
        });
    }

    function readAsText(fileEntry, callback) {
        fileEntry.file(function (file) {
            var reader = new FileReader();

            reader.onerror = errorHandler;
            reader.onload = function (e) {
                callback(e.target.result);
            };

            reader.readAsText(file);
        });
    }

    function readFile() {
        fileEntry.file(function (file) {
            readAsText(fileEntry, function (result) {
                console.log(result);
                parseProperties(result);
                startViewer();
            });
        });
    }

    function errorHandler(e) {
        console.error(e);
    }

    function parseProperties(txt) {
        var lines = txt.split(/\r\n|\r|\n/);
        for (var i = 0; i < lines.length; i++) {
            lines[i] = lines[i].match(/(.+?)=(.*)/);
        }

        viewerUrl = getProperty('url', lines, '');
        screenWidth = parseInt(getProperty('width', lines, 100));
        screenHeight = parseInt(getProperty('height', lines, 100));
    }

    function getProperty(name, lines, defaultValue) {
        for (var i = 0; i < lines.length; i++) {
            if (lines[i] && (lines[i].length == 3) && (lines[i][1] == name)) {
                return lines[i][2];
            }
        }
        return defaultValue;
    }

});
